function chartByYear(dom, chartdata, DtaInfo, item, json) {
    var myChart = echarts.init(dom);
    var option = {
        title: {
            text: (function () {
                console.log("json: ", json);
                if (json.comptype) {
                    return (DtaInfo && DtaInfo[json.comptype][item] + "\n" + item) || item;
                } else {
                    return (DtaInfo && DtaInfo[item] + "\n" + item) || item;
                }
            })(),
            left: 'center',
            top: '5%'
        },
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        legend: { show: false, data: chartdata.seriesname },
        grid: { left: '0%', right: '0%', bottom: '3%', containLabel: true },
        xAxis: [{ type: 'category', data: chartdata.xAxisdata, axisLabel: { interval: 0, margin: 10, rotate: 40 } }],
        yAxis: [{
            type: 'value',
            axisLabel: {
                formatter: function (value, index) {
                    if (Math.abs(value) > 1000000000000) {
                        return value / 1000000000000 + " 万亿";
                    } else if (Math.abs(value) > 100000000) {
                        return value / 100000000 + " 亿";
                    } else if (Math.abs(value) > 10000) {
                        return value / 10000 + " 万";
                    } else {
                        return value;
                    }
                },
                textStyle: { color: '#999', fontStyle: 'italic', }
            }
        }],
        series: [{
            name: chartdata.seriesname[0] ? chartdata.seriesname[0] : "",
            type: 'bar',
            data: chartdata.seriesname[0] ? chartdata.seriesdatalist[0].map(function (value) { return value[item] }) : [],
            markLine: chartdata.seriesname.length == 1 ? { label: { normal: { show: false } }, lineStyle: { normal: { type: 'dashed' } }, data: [[{ type: 'min' }, { type: 'max' }]] } : {}
        }, {
            name: chartdata.seriesname[1] ? chartdata.seriesname[1] : "",
            type: 'bar',
            data: chartdata.seriesname[1] ? chartdata.seriesdatalist[1].map(function (value) { return value[item] }) : [],
            markLine: chartdata.seriesname.length == 2 ? { label: { normal: { show: false } }, lineStyle: { normal: { type: 'dashed' } }, data: [[{ type: 'min' }, { type: 'max' }]] } : {}
        }, {
            name: chartdata.seriesname[2] ? chartdata.seriesname[2] : "",
            type: 'bar',
            data: chartdata.seriesname[2] ? chartdata.seriesdatalist[2].map(function (value) { return value[item] }) : [],
            markLine: chartdata.seriesname.length == 3 ? { label: { normal: { show: false } }, lineStyle: { normal: { type: 'dashed' } }, data: [[{ type: 'min' }, { type: 'max' }]] } : {}
        }, {
            name: chartdata.seriesname[3] ? chartdata.seriesname[3] : "",
            type: 'bar',
            data: chartdata.seriesname[3] ? chartdata.seriesdatalist[3].map(function (value) { return value[item] }) : [],
            markLine: chartdata.seriesname.length == 4 ? { label: { normal: { show: false } }, lineStyle: { normal: { type: 'dashed' } }, data: [[{ type: 'min' }, { type: 'max' }]] } : {}
        }],
        animation: false
    };
    myChart.setOption(option);
}

function extrDataByYear(json) {
    var dataList = json.list;
    var chartItem = [];
    _.each(dataList, function (ele) {
        chartItem = _.union(chartItem, _.keys(dataList[0]));
    });
    var reportdatelist = dataList.map(function (value, index, arr) {
        var dtime = new Date();
        dtime.setTime(value.report_date);
        return {
            xAxisdata: dtime.getFullYear(),
            seriesname: dtime.getMonth() + 1
        };
    });
    var xAxisdata = _.uniq(reportdatelist.map(function (value) {
        return value.xAxisdata
    }));
    var seriesname = _.uniq(reportdatelist.map(function (value) {
        return value.seriesname
    }));
    seriesname = _.sortBy(seriesname, function (n) {
        return n;
    });
    var seriesdatalist = [];
    for (var i = 0; i < seriesname.length; i++) {
        var flag = dataList.filter(function (element) {
            if (new Date(element.report_date).getMonth() + 1 == seriesname[i]) {
                return true;
            }
        });
        if (new Date(flag[0].report_date).getFullYear() != xAxisdata[0]) {
            flag = [{}].concat(flag);
        }
        if (new Date(flag[flag.length - 1].report_date).getFullYear() != xAxisdata[xAxisdata.length - 1]) {
            flag = flag.concat([{}]);
        }
        seriesdatalist.push(flag);
    }
    _.map(seriesdatalist, function (value, index, list) {
        _.map(value, function (value1, index, list2) {
            _.map(value1, function (value2, key, list3) {
                if ($.isArray(value2)) {
                    list3[key] = value2[0];
                    return value2[0];
                } else {
                    return value2;
                }
                return value2;
            })
            return value1;
        })
        return value;
    });
    return {
        xAxisdata: xAxisdata,
        seriesname: seriesname.map(function (value) {
            return value + "月"
        }),
        seriesdatalist: seriesdatalist,
        //chartItem:chartItem
        chartItem: _.difference(chartItem, ["report_date", "report_name", "ctime", "begindate", "enddate", "reporttype", "adjustdate", "accstacode", "accstaname", "sd", "ed", "month_num"])
    };
}

function getMarketRegion(symbol) {
    var marketRegion = "CN"
    $.ajax({
        url: "https://stock.xueqiu.com/v5/stock/batch/quote.json",
        type: "get",
        crossDomain: true,
        xhrFields: {
            withCredentials: true
        },
        async: false,
        dataType: "json",
        data: {
            symbol: symbol,
            extend: "detail"
        },
        success: function (json, textStatus) {
            if (textStatus == "success") {
                marketRegion = json.data.items[0].market.region
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("查询失败: ", XMLHttpRequest);
        }
    });
    return marketRegion;
}
function fetchData(metrictypes, symbol, size, callback) {
    var marketRegion = getMarketRegion(symbol).toLowerCase();
    url = "https://stock.xueqiu.com/v5/stock/finance/" + marketRegion + "/" + metrictypes + ".json"
    $.ajax({
        url: url,
        type: "get",
        crossDomain: true,
        xhrFields: {
            withCredentials: true
        },
        dataType: "json",
        data: {
            symbol: symbol,
            extend: "detail",
            type: "all",
            is_detail: true,
            count: size,
            timestamp: new Date().getTime()
        },
        success: function (json, textStatus) {
            if (textStatus == "success") {
                callback(json);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("查询失败: ", XMLHttpRequest);
        }
    });
}


function financeChart(metrictypes, stockCode, title) {
    fetchData(metrictypes, stockCode, 24, function (json) {
        if (json.data.list == null || json.data.list.length == 0) {
            console.log("查不到数据！", {
                time: 1500
            });
            return;
        }
        //json.data.list = json.data.list.reverse();
        var chartdata = extrDataByYear(json.data);
        var div = document.createElement("div");
        div.setAttribute("id", "newDiv");
        div.style.width = "100%";
        div.style.height = "600px";
        document.body.innerHTML = "";
        document.body.insertBefore(div, document.body.firstChild);
        var $body = $("#newDiv");
        switch (metrictypes) {
            case "indicator":
                $("title").html(json.data.quote_name + " ‧ 主要指标");
                _.each(chartdata.chartItem, function (element, index, list) {
                    if (element != "reportdate" && element != "enddate") {
                        var cwzb = $('<div class="canvasDiv" role="echart" style="width:330px;height:300px;float:left;"></div>');
                        $body.append(cwzb);
                        chartByYear(cwzb[0], chartdata, financeTableDataInfo.indicator, element, json.data);
                    }
                })
                break;
            case "income":
                $("title").html(json.data.quote_name + " ‧ 利润表");
                _.each(chartdata.chartItem, function (element, index, list) {
                    if (element != "reportdate" && element != "enddate") {
                        var cwzb = $('<div class="canvasDiv" role="echart" style="width:330px;height:300px;float:left;"></div>');
                        $body.append(cwzb);
                        chartByYear(cwzb[0], chartdata, financeTableDataInfo.income, element, json);
                    }
                })
                break;
            case "balance":
                $("title").html(json.data.quote_name + " ‧ 资产负债表");
                _.each(chartdata.chartItem, function (element, index, list) {
                    if (element != "renav__dropdownportdate" && element != "enddate") {
                        var cwzb = $('<div class="canvasDiv" role="echart" style="width:330px;height:300px;float:left;"></div>');
                        $body.append(cwzb);
                        chartByYear(cwzb[0], chartdata, financeTableDataInfo.balance, element, json);
                    }
                })
                break;
            case "cash_flow":
                $("title").html(json.data.quote_name + " ‧ 现金流量表");
                _.each(chartdata.chartItem, function (element, index, list) {
                    if (element != "reportdate" && element != "enddate") {
                        var cwzb = $('<div class="canvasDiv" role="echart" style="width:330px;height:300px;float:left;"></div>');
                        $body.append(cwzb);
                        chartByYear(cwzb[0], chartdata, financeTableDataInfo.cash_flow, element, json);
                    }
                })
                break;
            default:
        }
    });
};

$.financeChart = financeChart;

(function () {
    var thisHREF = document.location.href;
    var tmpHPage = thisHREF.split("/");
    switch (tmpHPage[tmpHPage.length - 2]) {
        case "indicator":
            $.financeChart("indicator", tmpHPage[tmpHPage.length - 1], "name" + " 主要财务指标");
            break;
        case "income":
            $.financeChart("income", tmpHPage[tmpHPage.length - 1], "name" + " 主要财务指标");
            break;
        case "balance":
            $.financeChart("balance", tmpHPage[tmpHPage.length - 1], "name" + " 主要财务指标");
            break;
        case "cash_flow":
            $.financeChart("cash_flow", tmpHPage[tmpHPage.length - 1], "name" + " 主要财务指标");
            break;
        default:
    }
})();